package com.atguigu.crowd.service.impl;

import com.atguigu.crowd.entity.Menu;
import com.atguigu.crowd.entity.MenuExample;
import com.atguigu.crowd.exception.IllegalOperationException;
import com.atguigu.crowd.mapper.MenuMapper;
import com.atguigu.crowd.service.api.MenuService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class MenuServiceImpl implements MenuService {
    @Autowired
    private MenuMapper menuMapper;

    @Override
    public List<Menu> getAll() {
        return menuMapper.selectByExample(new MenuExample());
    }

    @Override
    public void saveMenu(Menu menu) {
        menuMapper.insert(menu);
    }

    @Override
    public void updateMenu(Menu menu) {
        menuMapper.updateByPrimaryKeySelective(menu);
    }

    @Override
    public void removeMenu(Integer id) {
        if (countChildren(id) > 0) {
            throw new IllegalOperationException("存在子菜单，无法删除");
        } else {
            menuMapper.deleteByPrimaryKey(id);
        }
    }

    @Override
    public List<Menu> getChildren(Integer id) {
        MenuExample example = new MenuExample();
        MenuExample.Criteria criteria = example.createCriteria();
        criteria.andPidEqualTo(id);
        return menuMapper.selectByExample(example);
    }

    @Override
    public Integer countChildren(Integer id) {
        MenuExample example = new MenuExample();
        MenuExample.Criteria criteria = example.createCriteria();
        criteria.andPidEqualTo(id);
        return menuMapper.countByExample(example);
    }

    @Override
    public Menu getMenuById(Integer id) {
        return menuMapper.selectByPrimaryKey(id);
    }
}
